package com.jd.genie.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jd.genie.agent.llm.LLMSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Map;
import java.util.Properties;


/**
 * 配置工具类
 */
@Slf4j
public class LLMConfig {

    private static final String LLM_SETTINGS_JSON = """
            {
                "claude-3-7-sonnet-v1": {
                    "model": "claude-3-7-sonnet-v1",
                    "base_url": "<input llm server here>",
                    "apikey": "<input llm key here>",
                    "temperature": 0,
                    "interface_url": "/chat/completions",
                    "max_tokens": 8192,
                    "max_input_tokens": 128000
                }
            }
            """;

    private static final Map<String, LLMSettings> llmSettingsMap =
            JSON.parseObject(LLM_SETTINGS_JSON, new TypeReference<>() {
            });

    /**
     * 获取 LLM 配置
     */
    public static LLMSettings getLLMConfig(String modelName)
    {
        return llmSettingsMap.getOrDefault(modelName, getDefaultConfig());
    }

    /**
     * 加载 LLM 配置
     */
    private static LLMSettings getDefaultConfig()
    {
        Resource resource = new ClassPathResource("application.yml");
        YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
        yamlFactory.setResources(resource);
        Properties props = yamlFactory.getObject();

        // 创建默认配置
        return LLMSettings.builder()
                .model(props.getProperty("llm.default.model"))
                .maxTokens(Integer.parseInt(props.getProperty("llm.default.max_tokens")))
                .baseUrl(props.getProperty("llm.default.base_url"))
                .interfaceUrl(props.getProperty("llm.default.interface_url"))
                .apiKey(props.getProperty("llm.default.apikey"))
                .maxInputTokens(Integer.parseInt(props.getProperty("llm.default.max_input_tokens")))
                // --------------
                .temperature(0d)
                .build();
    }

}